package baibeiwallet.utils;

import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;


import com.alm.token.MyApp;
import com.alm.token.R;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.Keys;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthBlock;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;

import baibeiwallet.BaibeiWallet;
import baibeiwallet.solidity.CloudTreeToken;
import baibeiwallet.solidity.Token;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * TODO 写清楚此类的作用
 *
 * @author Try
 * @date 2018/9/14 17:21
 */
public class BaibeiTransferUtils {
    public final static String TAG = "BaibeiTransferUtils";

    public static Single<CloudTreeToken> loadContract2(BaibeiWallet wallet, String addr, BigInteger gasPrice, BigInteger gasLimit) {
        Credentials credentials = Credentials.create(wallet.getKeyPair());
        Log.i(TAG, "onClickDeploy: gasPrice = " + gasPrice);
        Log.i(TAG, "onClickDeploy: GAS_LIMIT = " + gasLimit);
        Web3j web3j = Web3jUtils.initWeb3j(null);
        return Single.fromCallable(() -> CloudTreeToken.load(addr, web3j, credentials, gasPrice, gasLimit))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());

    }
    public static Single<Token> loadContract(BaibeiWallet wallet, String addr, BigInteger gasPrice, BigInteger gasLimit) {
        Credentials credentials = Credentials.create(wallet.getKeyPair());
        Log.i(TAG, "onClickDeploy: gasPrice = " + gasPrice);
        Log.i(TAG, "onClickDeploy: GAS_LIMIT = " + gasLimit);
        Web3j web3j = Web3jUtils.initWeb3j(null);
        return Single.fromCallable(() -> Token.load(addr, web3j, credentials, gasPrice, gasLimit))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());

    }

    public static Single<BigInteger> balanceOf(Token token, String addr) {
        if (token == null) {
            Toast.makeText(MyApp.sInstance, MyApp.sInstance.getString(R.string.profile_hint_item33), Toast.LENGTH_SHORT).show();
            return Single.error(new NullPointerException( MyApp.sInstance.getString(R.string.profile_hint_item33)));
        }

        if (TextUtils.isEmpty(addr)) {
            Toast.makeText(MyApp.sInstance, MyApp.sInstance.getString(R.string.profile_hint_item34), Toast.LENGTH_SHORT).show();
            return Single.error(new NullPointerException(MyApp.sInstance.getString(R.string.profile_hint_item34)));
        }

        return Single.fromCallable(() -> token.balanceOf(Keys.toChecksumAddress(addr))
                .send())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 返回指定地址账户的余额。
     * @param address
     * @return
     */
    public static Single<BigInteger> getBalanceForETH(String address) {
        if (TextUtils.isEmpty(address)) {
            return Single.error(new NullPointerException(MyApp.sInstance.getString(R.string.profile_hint_item34)));
        }

        String addr = address.startsWith("0x") ? address : Keys.toChecksumAddress(address);
        Web3j web3j = Web3jUtils.initWeb3j(null);
        return Single.fromCallable(() -> web3j
                .ethGetBalance(addr, DefaultBlockParameterName.LATEST)
                .send()
                .getBalance())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 返回当前的gas价格，单位：wei。
     * @return
     */
    public static Single<BigInteger> getGasForETH() {
//        if (TextUtils.isEmpty(address)) {
//            return Single.error(new NullPointerException("转账地址为空！"));
//        }

//        String addr = address.startsWith("0x") ? address : Keys.toChecksumAddress(address);
        Web3j web3j = Web3jUtils.initWeb3j(null);
        return Single.fromCallable(() -> web3j
                .ethGasPrice()
                .send()
                .getGasPrice())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 区块账单信息
     * @return
     */
    public static Single<BigInteger> getGasForETH1() {
        Web3j web3j = Web3jUtils.initWeb3j(null);
        List<EthBlock.TransactionResult> txs = null;
        try {
            txs = web3j.ethGetBlockByNumber(DefaultBlockParameterName.LATEST, true).send().getBlock().getTransactions();

            for (EthBlock.TransactionResult transactionResult : txs) {
                EthBlock.TransactionObject transaction = (EthBlock.TransactionObject)transactionResult.get();
                System.out.println(transaction.getFrom());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return Single.fromCallable(() -> web3j
                .ethGasPrice()
                .send()
                .getGasPrice())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

}
